#!/bin/bash

# 停止占用端口50051的进程
PORT=50051
echo "🔍 Checking for processes on port $PORT..."
lsof -ti:$PORT | xargs kill -9 2>/dev/null || echo "Port $PORT is free"

# 等待端口释放
sleep 1

# 编译项目
echo "🔨 Building project..."
cargo build

if [ $? -eq 0 ]; then
    echo "✅ Build successful"
    
    # 启动新的服务器
    echo "🚀 Starting server..."
    nohup cargo run --bin server > server.log 2>&1 &
    
    # 获取进程ID
    SERVER_PID=$!
    echo "📝 Server started with PID: $SERVER_PID"
    
    # 等待服务器启动
    echo "⏳ Waiting for server to start..."
    sleep 3
    
    # 检查服务器是否正在运行
    if ps -p $SERVER_PID > /dev/null; then
        echo "✅ Server is running on port $PORT"
        echo "📋 Server logs: tail -f server.log"
    else
        echo "❌ Server failed to start"
        echo "📋 Check server.log for errors"
    fi
else
    echo "❌ Build failed"
    exit 1
fi